<?php

namespace App\Http\Controllers\Bap;

use App\Http\Controllers\Controller;
use App\Models\Currency;
use App\Models\EmailSms;
use App\Models\LoginLog;
use App\Models\Message;
use App\Models\PhoneSms;
use App\Models\Property;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Library\Yunxin;

class LoginController extends Controller
{
    /**
     * 登录.
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function log_in(Request $request)
    {
        //验证必传参数
        if (!$request->has('account', 'password')) {
            //错误提示
            return respF(1003);
        }
        //账号
        $account = $request->get('account');
        //密码
        $password = $request->get('password');
        //判断是邮箱还是手机
        if (isPhone($account)) {
            $user = User::where('phone', $account)->first();
        } else if(isEmail($account)) {
            $user = User::where('email', $account)->first();
        } else {
            return respF(2011);
        }
        if (!$user) {
            //账号未注册
            return respF(4004);
        }
        //没有用户
        if ($user->password != md5($password)) {
            //账号或密码错误
            return respF(2010);
        }
        //更新登录信息 2018-5-5
        $map['token'] = md5(time());
        $map['islogin'] = 1;
        $user_updata = $user->update($map);
        if (collect($user_updata)->count() == 0) {
            //更新出错
            return respF(3023);
        }
        //客户端IP
        $ip = $request->getClientIp();
        //根据IP获取地理位置
        //$lookup = GetIpLookup($ip);
        //获取成功
        $address = '';
        //if ($lookup)
            //拼接地址
            //$address = $lookup['country'].$lookup['province'].$lookup['city'];
        //写入登录历史
        LoginLog::create([
            'uid' => $user->id,
            'client' => 'web',
            'ip' => $ip,
            'address' => $address,
            'status' => 1,
        ]);
        //调用云信更新信息
        $model = new Yunxin\Yunxin();
        $name = $user->nickname;
        $id = $user->id;
        $img = config('alioss.host').'/'.$user->headimg;
        $arr = $model->change_yx($id, $name, $img, $map['token']);

        $info = [];
        //用户ID
        $info['uid'] = $user->id;
        //用户账号
        $info['account'] = $user->account;
        //用户昵称
        $info['nickname'] = $user->nickname;
        //用户邮箱
        $info['email'] = $user->email;
        //用户手机
        $info['phone'] = $user->phone;
        //用户头像
        $info['headimg'] = config('alioss.host').$user->headimg;
        //实名认证状态
        $info['real_status'] = $user->real_status;
        //用户分类
        $info['type'] = $user->type;
        //是否设置交易密码
        if (strlen($user->pay_pass) > 0) {
            $info['is_pay_pass'] = 1;
        } else {
            $info['is_pay_pass'] = 0;
        }

        $data['info'] = $info;
        //支付宝信息
        $data['alipay'] = $user->user_alipay;
        //微信支付信息
        $data['wechat'] = $user->user_wechat;
        //实名认证信息
        $autonym = $user->autonym()->select('name', 'indentity_card', 'back_card', 'front_card', 'status', 'note')->first();
        if ($autonym) {
            $autonym->front_card = config('alioss.host').'/'.$autonym->front_card;
            $autonym->back_card = config('alioss.host').'/'.$autonym->back_card;
            $autonym->hand_card = config('alioss.host').'/'.$autonym->hand_card;
        }
        $data['autonym'] = $autonym;
        $data['token'] = $map['token'];
        $data['islogin'] = $user->islogin;

        return response()->json(['status' => 1, 'msg' => '登录成功', 'data' => $data]);
    }

    /**
     * 发送邮箱验证码
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function send_email_code(Request $request)
    {
        $email = $request->get('email');
        $type = $request->get('type');
        //验证参数
        if (empty($email) || empty($type)) {
            return respF(1003);
        }
        //验证邮箱
        if (!isEmail($email)) {
            //账号格式不正确
            return respF(2011);
        }
        //查找用户
        $user = User::where('email', $email)->first();
        //注册时邮箱必须未注册
        if ($type == 2) {
            if (collect($user)->count() > 0) {
                return respF(2019);
            }
        }
        //非注册判断用户是否存在
        if ($type != 2) {
            if (collect($user)->count() == 0) {
                return respF(1001);
            }
        }
        //查找验证码
        $sms = EmailSms::where(['email' => $email, 'type' => $type])->orderBy('created_at', 'desc')->first();
        //如果存在
        if (collect($sms)->count() > 0) {
            //判断是否过期
            $expire_time = $sms->expire_time;
            //未过期，不能发
            if (time() < $expire_time) {
                //验证码已发送 （不能报错）
                //return response()->json(['status' => 1, 'msg' => '验证码已发送']);
                return respF(3009);
            }
        }

        $name = 'admin';
        $code = getCode();
        $flag = Mail::raw('你好，您的验证码是:   '.$code, function ($message) use ($email) {
            $to = $email;
            $message->to($to)->subject('系统邮件');
        });
        /*$data['email'] = $email;
        $data['code'] = $code;
        $data['name'] = $name;
        $flag = Mail::send('email', $data, function ($message) use ($data) {
        $message->to($data['email'], $data['code'])->subject('系统邮件');
        });*/

        if (!$flag) {
            $time = time();
            $expire_time = time() + 300;
            $res = EmailSms::create(
                [
                    'email' => $email,
                    'type' => $type,
                    'code' => $code,
                    'send_time' => $time,
                    'expire_time' => $expire_time,
                ]
            );

            return response()->json(['status' => 1, 'msg' => '发送成功', 'expire_time' => $res->expire_time]);
        } else {
            return respF(1023);
        }
    }

    /**
     * 发送手机验证码
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function send_phone_code(Request $request)
    {
        $phone = $request->get('phone');
        $type = $request->get('type');
        //验证参数
        if (empty($phone) || empty($type)) {
            return respF(1003);
        }
        //验证手机
        if (!isPhone($phone)) {
            //账号格式不正确
            return respF(2011);
        }
        //查找用户
        $user = User::where('phone', $phone)->first();
        //注册时判断用户是否已注册
        if ($type == 2) {
            if (collect($user)->count() > 0) {
                return respF(2020);
            }
        }
        //非注册判断用户是否存在
        if ($type != 2) {
            if (collect($user)->count() == 0) {
                return respF(1001);
            }
        }

        //查找验证码
        $sms = PhoneSms::where(['phone' => $phone, 'type' => $type])->orderBy('created_at', 'desc')->first();
        //如果存在
        if (collect($sms)->count() > 0) {
            //判断是否过期
            $expire_time = $sms->expire_time;
            //未过期，不能发
            if (time() < $expire_time) {
                //验证码已发送 （不能报错）
                return respF(3009);
                //return response()->json(['status' => 1, 'msg' => '验证码已发送']);
            }
        }

        $template = getTemplate($type); //根据类型获取短信模板
        $code = getCode();
        $expired = 300;
        //$result = Cloud::sendTemplateSMS($phone, [$code, $expired.'秒'], $template); //发送短信验证码
        //发送失败
        //if (!$result['resultStatus']) {
        //throw new Exception("验证码发送失败！");
        //return response()->json(['status' => 0, 'msg' => '发送失败']);
        //} else {
        $time = time();
        $expire_time = time() + $expired;
        $res = PhoneSms::create(
            [
                'phone' => $phone,
                'type' => $type,
                'code' => $code,
                'send_time' => $time,
                'expire_time' => $expire_time,
            ]
        );

        return response()->json(['status' => 1, 'msg' => '发送成功', 'expire_time' => $res->expire_time]);
        //}
    }

    /**
     * 手机注册.
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function phone_register(Request $request)
    {
        //验证必传参数
        if (!$request->has('phone', 'code', 'password', 'repass')) {
            return respF(1003);
        }
        //手机
        $phone = $request->get('phone');
        //验证码
        $code = $request->get('code');
        //密码
        $password = $request->get('password');
        //确认密码
        $repass = $request->get('repass');
        //验证手机
        if (!isPhone($phone)) {
            //错误提示
            return respF(2029);
        }
        //验证两次密码
        if ($password != $repass) {
            //错误提示
            return respF(2030);
        }
        //验证是否注册
        $check = User::where(['phone' => $phone, 'type' => 1])->first();
        //手机已存在
        if ($check) {
            //错误提示
            return respF(2020);
        }
        /*$sms = PhoneSms::where(['phone' => $phone, 'type' => 2])->orderBy('created_at', 'desc')->first();
        if (!$sms) {
        return response()->json(['status' => 0, 'msg' => '请获取验证码']);
        }
        if ($sms->expire_time < time()) {
        return response()->json(['status' => 0, 'msg' => '验证码已过期']);
        }
        if ($code != $sms->code) {
        return response()->json(['status' => 0, 'msg' => '验证码不正确']);
        }*/
        //写入数据库
        $res = User::create([
            'account' => getAccount(),
            'nickname' => getNickname(),
            'email' => '',
            'phone' => $phone,
            'password' => md5($password),
            'pay_pass' => '',
            'headimg' => randomHeadimg(),
            'token' => md5(time()),
        ]);
        //写入系统消息
        Message::create([
            'admin_id' => 0,
            'uid' => $res->id,
            'title' => '会员注册',
            'content' => $res->nickname.'注册成功',
            'type' => 1,
            'tpl_id' => 0,
        ]);
        //调用云信注册
        $model = new Yunxin\Yunxin();
        $name = $res->nickname;
        $id = $res->id;
        $img = config('alioss.host').'/'.$res->headimg;
        $arr = $model->register_yx($id, $name, $img, $res->token);
        if ($arr['status'] = 1) {
            $yx_check = User::where('id', $id)->update(['yx_status' => 2]);
        }

        //所有币种ID
        /*$cids = Currency::where(['online_switch' => 1])->pluck('id')->toArray();
        //生成资产详情
        foreach ($cids as $cid) {
            Property::create([
                'cid'     => $cid,
                'uid'     => $res->id,
                'balance' => 0,
                'blocked' => 0,
                'total'   => 0,
            ]);
        }*/
        //用户ID
        $data['uid'] = $res->id;
        //用户账号
        $data['account'] = $res->account;
        //昵称
        $data['nickname'] = $res->nickname;
        //邮箱
        $data['email'] = $res->email;
        //手机
        $data['phone'] = $res->phone;
        //头像
        $data['headimg'] = $res->headimg;
        //实名状态
        $data['real_status'] = $res->real_status;
        //成功提示
        return response()->json(['status' => 1, 'msg' => '注册成功', 'data' => $data]);
    }

    /**
     * 邮箱注册.
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function email_register(Request $request)
    {
        //验证必传参数
        if (!$request->has('email', 'password', 'repass')) {
            //错误提示
            return respF(1003);
        }
        //邮箱
        $email = $request->get('email');
        //密码
        $password = $request->get('password');
        //确认密码
        $repass = $request->get('repass');
        //两次密码验证
        if ($password != $repass) {
            //错误提示
            return respF(2030);
        }
        //查找邮箱
        $check = User::where(['email' => $email, 'type' => 1])->first();
        //已存在
        if ($check) {
            //错误提示
            return respF(2019);
        }
        //写入用户表
        $res = User::create([
            'account' => getAccount(),
            'nickname' => getNickname(),
            'email' => $email,
            'phone' => '',
            'password' => md5($password),
            'pay_pass' => '',
            'headimg' => randomHeadimg(),
            'token' => md5(time()),
        ]);
        //写入系统消息表
        Message::create([
            'admin_id' => 0,
            'uid' => $res->id,
            'title' => '会员注册',
            'content' => $res->nickname.'注册成功',
            'type' => 1,
            'tpl_id' => 0,
        ]);
        //调用云信注册
        $model = new Yunxin\Yunxin();
        $name = $res->nickname;
        $id = $res->id;
        $img = config('alioss.host').'/'.$res->headimg;
        $arr = $model->register_yx($id, $name, $img, $res->token);
        if ($arr['status'] = 1) {
            $yx_check = User::where('id', $id)->update(['yx_status' => 2]);
        }
        //币种ID
        /*$cids = Currency::where(['online_switch' => 1])->pluck('id')->toArray();
        //生成资产详情
        foreach ($cids as $cid) {
            Property::create([
                'cid'     => $cid,
                'uid'     => $res->id,
                'balance' => 0,
                'blocked' => 0,
                'total'   => 0,
            ]);
        }*/
        //用户ID
        $data['uid'] = $res->id;
        //用户账号
        $data['account'] = $res->account;
        //用户昵称
        $data['nickname'] = $res->nickname;
        //用户邮箱
        $data['email'] = $res->email;
        //用户手机
        $data['phone'] = $res->phone;
        //用户头像
        $data['headimg'] = $res->headimg;
        //实名状态
        $data['real_status'] = $res->real_status;
        //成功提示
        return response()->json(['status' => 1, 'msg' => '注册成功', 'data' => $data]);
    }

    /**
     * 忘记密码
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function forget_password(Request $request)
    {
        //验证必传参数
        if (!$request->has('account', 'password', 'repass', 'code')) {
            //错误提示
            return respF(1003);
        }
        //手机号或邮箱
        $account = $request->get('account');
        //密码
        $password = $request->get('password');
        //确认密码
        $repass = $request->get('repass');
        //验证码
        $code = $request->get('code');
        //验证两次密码是否一致
        if ($password != $repass) {
            //错误提示
            return respF(2030);
        }
        //判断是手机还是邮箱
        if (isPhone($account)) {
            //根据手机查找用户
            $user = User::where(['phone' => $account])->first();
            //手机验证码记录
            $check = PhoneSms::where(['phone' => $account, 'type' => 3])
                ->orderBy('created_at', 'desc')->first();
        } elseif (isEmail($account)) {
            //根据邮箱查找用户
            $user = User::where(['email' => $account])->first();
            //邮箱验证码记录
            $check = EmailSms::where(['email' => $account, 'type' => 3])
                ->orderBy('created_at', 'desc')->first();
        } else {
            //非手机非邮箱
            return respF(3011);
        }
        //判断密码
        if (md5($password) == $user->password) {
            //错误提示
            return respF(2013);
        }
        /*if (!$check) {
        return response()->json(['status' => 0, 'msg' => '请获取验证码']);
        }
        if ($check->expire_time < time()) {
        return response()->json(['status' => 0, 'msg' => '验证码已过期']);
        }
        if ($code != $check->code) {
        return response()->json(['status' => 0, 'msg' => '验证码不正确']);
        }*/
        //更新密码
        $user->update([
            'password' => md5($password),
        ]);
        //用户ID
        $data['uid'] = $user->id;
        //用户账号
        $data['account'] = $user->account;
        //用户昵称
        $data['nickname'] = $user->nickname;
        //用户邮箱
        $data['email'] = $user->email;
        //用户手机
        $data['phone'] = $user->phone;
        //用户头像
        $data['headimg'] = $user->headimg;
        //实名状态
        $data['real_status'] = $user->real_status;
        //成功提示
        return response()->json(['status' => 1, 'msg' => '修改成功', 'data' => $data]);
    }

    /**
     * 设置支付密码
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function set_pay_pass(Request $request)
    {
        //验证必传参数
        if (!$request->has('uid', 'pay_pass')) {
            return respF(1003);
        }
        //用户ID
        $uid = $request->get('uid');
        //交易密码
        $pay_pass = $request->get('pay_pass');
        //确认密码
        $repass = $request->get('repass');
        //验证两次密码是否一致
        if ($pay_pass != $repass) {
            //错误提示
            return respF(2030);
        }
        //查找用户
        $user = User::find($uid);
        //用户不存在
        if (!$user) {
            //错误提示
            return respF(1001);
        }
        //判断交易密码
        if (strlen($user->pay_pass) > 1) {
            //错误提示
            return respF(2014);
        }
        //更新交易密码
        $user->update(['pay_pass' => md5($pay_pass)]);
        //成功提示
        return response()->json(['status' => 1, 'msg' => '设置成功']);
    }

    /**
     * 修改登录密码
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function update_password(Request $request)
    {
        //验证必传参数
        if (!$request->has('uid', 'password', 'old_pass', 'repass')) {
            //错误提示
            return respF(1003);
        }
        //用户ID
        $uid = $request->get('uid');
        //密码
        $password = $request->get('password');
        //旧密码
        $old_pass = $request->get('old_pass');
        //确认密码
        $repass = $request->get('repass');
        //验证两次密码是否一致
        if ($password != $repass) {
            //错误提示
            return respF(2030);
        }
        //验证新旧密码
        if ($password == $old_pass) {
            //错误提示
            return respF(2013);
        }
        //查找用户
        $user = User::find($uid);
        //用户不存在
        if (!$user) {
            //错误提示
            return respF(1001);
        }
        //验证密码
        if ($user->password != md5($old_pass)) {
            //错误提示
            return respF(2016);
        }
        //验证密码和交易密码一致性
        if ($user->password == md5($password)) {
            //错误提示
            return respF(2013);
        }
        if ($user->pay_pass == md5($password)) {
            return respF(2018);
        }

        //更新登录密码
        $user->update(['password' => md5($password)]);
        //成功提示
        return response()->json(['status' => 1, 'msg' => '修改成功']);
    }

    /**
     * 修改交易密码
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function update_pay_pass(Request $request)
    {
        //验证必传参数
        if (!$request->has('uid', 'password', 'old_pass', 'pay_pass', 'repass')) {
            //错误提示
            return respF(1003);
        }
        //用户ID
        $uid = $request->get('uid');
        //登录密码
        $password = $request->get('password');
        //旧密码
        $old_pass = $request->get('old_pass');
        //新密码
        $pay_pass = $request->get('pay_pass');
        //确认密码
        $repass = $request->get('repass');
        //验证两次密码是否一致
        if ($repass != $pay_pass) {
            //错误提示
            return respF(2030);
        }
        //验证新旧密码
        if ($pay_pass == $old_pass) {
            //错误提示
            return respF(2013);
        }
        //查找用户
        $user = User::find($uid);
        //用户不存在
        if (!$user) {
            //错误提示
            return respF(1001);
        }
        //验证登录密码
        if ($user->password != md5($password)) {
            //错误提示
            return respF(2017);
        }
        //验证交易密码
        if ($user->pay_pass != md5($old_pass)) {
            //错误提示
            return respF(2026);
        }

        if ($user->password == md5($pay_pass)) {

            return respF(2018);
        }

        //更新交易密码
        $user->update(['pay_pass' => md5($pay_pass)]);
        //成功提示
        return response()->json(['status' => 1, 'msg' => '修改成功']);
    }

    /**
     * 设置修改交易密码通过邮箱验证码
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function update_pass_by_code(Request $request)
    {
        //验证必传参数
        if (!$request->has('account', 'code', 'pay_pass', 'repass')) {
            //错误提示
            return respF(1003);
        }
        //账号
        $account = $request->get('account');
        //验证码
        $code = $request->get('code');
        //交易密码
        $pay_pass = $request->get('pay_pass');
        //确认密码
        $repass = $request->get('repass');
        //判断手机
        if (isPhone($account)) {
            //根据手机查找用户
            $user = User::where(['phone' => $account])->first();
            //根据手机查找验证码
            $check = PhoneSms::where(['phone' => $account, 'type' => 4])
                ->orderBy('created_at', 'desc')->first();
        } else {
            //根据邮箱查找用户
            $user = User::where(['email' => $account])->first();
            //根据邮箱查找验证码
            $check = EmailSms::where(['email' => $account, 'type' => 4])
                ->orderBy('created_at', 'desc')->first();
        }
        //用户不存在
        if (!$user) {
            //错误提示
            return respF(1001);
        }

        //验证密码
        if ($user->password == md5($pay_pass))
            return respF(2018);//交易密码不能与登录密码相同
        if ($user->pay_pass == md5($pay_pass))
            return respF(2035);//不能更改为原支付密码  --by zrc 6-2

        /*
        if (!$check) {
        return response()->json(['status' => 0, 'msg' => '请获取验证码']);
        }
        if ($check->expire_time < time()) {
        return response()->json(['status' => 0, 'msg' => '验证码已过期']);
        }
        if ($code != $check->code) {
        return response()->json(['status' => 0, 'msg' => '验证码不正确']);
        }*/
        //更新交易密码
        $user->update(['pay_pass' => md5($pay_pass)]);
        //成功提示
        return response()->json(['status' => 1, 'msg' => '修改成功']);
    }
}
